package com.conversationboard.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.StringTokenizer;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

public class BoardAdminList {

	private Set<Integer> boardAdminList = new LinkedHashSet<Integer>();


	public String toString() {

		StringBuilder buffer = new StringBuilder();

		for (Integer i : boardAdminList) {
			buffer.append(i);
			buffer.append(",");
		}

		buffer.deleteCharAt(buffer.length() - 1);

		return buffer.toString();
	}


	public BoardAdminList() {
	}


	public void setBoardAdminList(Set<Integer> boardAdminList) {
		this.boardAdminList = boardAdminList;
	}


	public Set<Integer> getBoardAdminList() {
		return this.boardAdminList;
	}


	public BoardAdminList(String boardAdminListFromDatabase) {

		/* Parse the comma-delimited list of board IDs */

		if (boardAdminListFromDatabase == null) {
			return;
		}

		this.boardAdminList.clear();
		StringTokenizer tokeniser = new StringTokenizer(boardAdminListFromDatabase, ",");

		while (tokeniser.hasMoreTokens()) {
			int boardId = Integer.parseInt(tokeniser.nextToken());
			this.boardAdminList.add(boardId);
		}

	}


	public void makeAdmin(int boardId) {
		this.boardAdminList.add(boardId);
	}


	public void persist(String userId) throws SQLException {

		Connection connection = null;

		try {

			connection = Database.getConnection();
			connection.setAutoCommit(false);

			PreparedStatement statement = connection.prepareStatement(Queries.STORE_BOARD_ADMINS);
			statement.setString(1, this.toString());
			statement.setString(2, userId);

			statement.executeUpdate();
			statement.close();

			statement = connection.prepareStatement(Queries.MAKE_BOARD_ADMIN);
			statement.setString(1, userId);
			statement.executeUpdate();

			statement.close();

			connection.commit();

		} catch (SQLException e) {
			connection.rollback();
			throw e;
		} finally {
			Database.close(connection);
		}

	}


	public boolean isAdmin(int boardId) {

		for (Integer i : boardAdminList) {
			if (boardId == i) {
				return true;
			}
		}

		return false;
	}

}
